package com.zhentao.controller;

import com.zhentao.common.PageResult;
import com.zhentao.common.Result;
import com.zhentao.dto.DynamicQueryDTO;
import com.zhentao.dto.PublishDynamicDTO;
import com.zhentao.service.PublishService;
import com.zhentao.service.UserDynamicsService;
import com.zhentao.service.InteractionService;
import com.zhentao.service.CommentService;
import com.zhentao.entity.DynamicComments;
import org.springframework.web.bind.annotation.RequestBody;
import com.zhentao.dto.CommentCreateDTO;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import com.zhentao.vo.DynamicVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * 用户动态控制器
 */
@RestController
@RequestMapping("/api/dynamic")
@Validated
public class DynamicController {

    @Autowired
    private UserDynamicsService userDynamicsService;
    @Autowired
    private InteractionService interactionService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private PublishService publishService;
    @Autowired
    private com.zhentao.service.MediaUploadService mediaUploadService;

    /**
     * 分页查询动态列表
     * @param queryDTO 查询条件
     * @return 动态列表
     */
    @GetMapping("/list")
    public Result<PageResult<DynamicVO>> getDynamicList(@Valid DynamicQueryDTO queryDTO) {
        try {
            PageResult<DynamicVO> result = userDynamicsService.getDynamicList(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询动态列表失败：" + e.getMessage());
        }
    }

    /**
     * 查询动态详情
     * @param dynamicId 动态ID
     * @param userId 当前用户ID（可选）
     * @return 动态详情
     */
    @GetMapping("/detail/{dynamicId}")
    public Result<DynamicVO> getDynamicDetail(
            @PathVariable Integer dynamicId,
            @RequestParam(required = false) Integer userId) {
        try {
            DynamicVO dynamic = userDynamicsService.getDynamicDetail(dynamicId, userId);
            if (dynamic == null) {
                return Result.error(404, "动态不存在");
            }
            return Result.success(dynamic);
        } catch (Exception e) {
            return Result.error("查询动态详情失败：" + e.getMessage());
        }
    }

    /**
     * 查询某个用户的动态列表
     * @param userId 用户ID
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param currentUserId 当前登录用户ID（可选）
     * @return 动态列表
     */
    @GetMapping("/user/{userId}")
    public Result<PageResult<DynamicVO>> getUserDynamics(
            @PathVariable Integer userId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer currentUserId) {
        try {
            DynamicQueryDTO queryDTO = new DynamicQueryDTO();
            queryDTO.setTargetUserId(userId);
            queryDTO.setPageNum(pageNum);
            queryDTO.setPageSize(pageSize);
            queryDTO.setCurrentUserId(currentUserId);
            
            PageResult<DynamicVO> result = userDynamicsService.getUserDynamics(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询用户动态失败：" + e.getMessage());
        }
    }

    /**
     * 获取推荐动态列表（审核通过且公开）
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param userId 当前用户ID（可选）
     * @return 动态列表
     */
    @GetMapping("/recommend")
    public Result<PageResult<DynamicVO>> getRecommendDynamics(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer userId) {
        try {
            DynamicQueryDTO queryDTO = new DynamicQueryDTO();
            queryDTO.setPageNum(pageNum);
            queryDTO.setPageSize(pageSize);
            queryDTO.setCurrentUserId(userId);
            queryDTO.setAuditStatus(1); // 审核通过
            queryDTO.setVisibility(1);  // 公开
            
            PageResult<DynamicVO> result = userDynamicsService.getDynamicList(queryDTO);
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("查询推荐动态失败：" + e.getMessage());
        }
    }

    // ====== 互动接口 ======
    /**
     * 点赞
     */
    @PostMapping("/like")
    public Result<String> like(@RequestParam Integer dynamicId,
                               @RequestParam(required = false, defaultValue = "1") Integer userId) {
        try {
            interactionService.like(userId, dynamicId);
            return Result.success("OK", "success");
        } catch (Exception e) {
            return Result.error("点赞失败：" + e.getMessage());
        }
    }

    // ====== 发布动态 ======
    @PostMapping("/publish")
    public Result<Integer> publish(@RequestBody PublishDynamicDTO dto) {
        try {
            if (dto.getUserId() == null) dto.setUserId(1);
            if (dto.getMediaType() == null) dto.setMediaType(1);
            if (dto.getVisibility() == null) dto.setVisibility(1);
            Integer dynamicId = publishService.publish(dto);
            return Result.success(dynamicId);
        } catch (Exception e) {
            return Result.error("发布动态失败：" + e.getMessage());
        }
    }

    /**
     * 发布动态媒体上传（图片/视频）
     */
    @PostMapping(value = "/publish/upload", consumes = {"multipart/form-data"})
    public Result<String> uploadDynamicMedia(@RequestParam("file") MultipartFile file) {
        try {
            String url = mediaUploadService.uploadDynamicMedia(file);
            return Result.success(url);
        } catch (Exception e) {
            return Result.error("媒体上传失败：" + e.getMessage());
        }
    }

    /**
     * 发布动态批量媒体上传（多张图片）
     */
    @PostMapping(value = "/publish/upload/batch", consumes = {"multipart/form-data"})
    public Result<java.util.List<String>> uploadDynamicMediaBatch(@RequestParam("files") MultipartFile[] files) {
        try {
            java.util.List<String> urls = mediaUploadService.uploadDynamicMediaBatch(files);
            return Result.success(urls);
        } catch (Exception e) {
            return Result.error("批量媒体上传失败：" + e.getMessage());
        }
    }

    /**
     * 文件上传大小限制异常处理
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public Result<String> handleMaxUploadSizeExceeded(MaxUploadSizeExceededException e) {
        return Result.error("文件大小超过限制，单个文件最大10MB，请压缩后重试");
    }

    // ====== 评论接口 ======
    @PostMapping("/comment")
    public Result<String> addComment(@RequestBody CommentCreateDTO dto) {
        try {
            String[] imageUrls = null;
            if (dto.getImageList() != null && !dto.getImageList().isEmpty()) {
                imageUrls = dto.getImageList().toArray(new String[0]);
            } else if (dto.getImages() != null && !dto.getImages().trim().isEmpty()) {
                imageUrls = dto.getImages().split(",");
            }
            Integer uid = dto.getUserId() != null ? dto.getUserId() : 1;
            Integer parentId = dto.getParentCommentId() != null ? dto.getParentCommentId() : 0;
            commentService.addComment(uid, dto.getDynamicId(), dto.getContent(), imageUrls, parentId);
            return Result.success("OK", "success");
        } catch (Exception e) {
            return Result.error("发表评论失败：" + e.getMessage());
        }
    }

    @GetMapping("/comment/list/{dynamicId}")
    public Result<PageResult<DynamicComments>> listComments(@PathVariable Integer dynamicId,
                                                            @RequestParam(defaultValue = "1") Integer pageNum,
                                                            @RequestParam(defaultValue = "10") Integer pageSize) {
        try {
            return Result.success(commentService.listComments(dynamicId, pageNum, pageSize));
        } catch (Exception e) {
            return Result.error("查询评论失败：" + e.getMessage());
        }
    }

    @PostMapping("/comment/like")
    public Result<String> likeComment(@RequestParam Integer commentId,
                                      @RequestParam(required = false, defaultValue = "1") Integer userId) {
        try {
            commentService.likeComment(userId, commentId);
            return Result.success("OK", "success");
        } catch (Exception e) {
            return Result.error("评论点赞失败：" + e.getMessage());
        }
    }

    

    @DeleteMapping("/comment/like/{commentId}")
    public Result<String> unlikeComment(@PathVariable Integer commentId,
                                        @RequestParam(required = false, defaultValue = "1") Integer userId) {
        try {
            commentService.unlikeComment(userId, commentId);
            return Result.success("OK", "success");
        } catch (Exception e) {
            return Result.error("取消评论点赞失败：" + e.getMessage());
        }
    }

    /**
     * 取消点赞
     */
    @DeleteMapping("/like/{dynamicId}")
    public Result<String> unlike(@PathVariable Integer dynamicId,
                                 @RequestParam(required = false, defaultValue = "1") Integer userId) {
        try {
            interactionService.unlike(userId, dynamicId);
            return Result.success("OK", "success");
        } catch (Exception e) {
            return Result.error("取消点赞失败：" + e.getMessage());
        }
    }

    /**
     * 收藏
     */
    @PostMapping("/favorite")
    public Result<String> favorite(@RequestParam Integer dynamicId,
                                   @RequestParam(required = false, defaultValue = "1") Integer userId) {
        try {
            interactionService.favorite(userId, dynamicId);
            return Result.success("OK", "success");
        } catch (Exception e) {
            return Result.error("收藏失败：" + e.getMessage());
        }
    }

    /**
     * 取消收藏
     */
    @DeleteMapping("/favorite/{dynamicId}")
    public Result<String> unfavorite(@PathVariable Integer dynamicId,
                                     @RequestParam(required = false, defaultValue = "1") Integer userId) {
        try {
            interactionService.unfavorite(userId, dynamicId);
            return Result.success("OK", "success");
        } catch (Exception e) {
            return Result.error("取消收藏失败：" + e.getMessage());
        }
    }

    
}


